from sqlalchemy.orm import Session, joinedload, selectinload

from ..crud.image_crud import get_image_by_id
from ..crud.paper_crud import get_paper_by_id
from ..models.folders_model import Folder
from ..crud.textbook_crud import get_textbook_by_id
from ..crud.video_crud import get_video_by_id
def get_user_folder_tree(db: Session, user_id: int):
    folders = db.query(Folder).options(
        joinedload(Folder.sources),
        joinedload(Folder.children)  # 预加载 children
    ).filter(Folder.user_id == user_id).all()

    if not folders:
        return {user_id: []}

    # 2. 构建 id -> folder 字典
    folder_map = {folder.id: folder for folder in folders}

    # 3. 构建树形结构
    root_folders = []
    for folder in folders:
        if folder.parent_id is None:
            root_folders.append(folder)
        else:
            parent = folder_map.get(folder.parent_id)
            if parent:
                # 确保 parent 有 children 属性
                if not hasattr(parent, 'children'):
                    parent.children = []
                # 避免重复添加子节点
                if folder not in parent.children:
                    parent.children.append(folder)
    def get_resource(folder):
        sources_List = []
        print(folder.id)
        if folder.sources:
            for source in folder.sources:
                if source.resource_type == 'textbook':
                    a={
                        "source_type":source.resource_type,
                        "textbook":get_textbook_by_id(db,source.resource_id)
                    }
                    sources_List.append(a)
                elif source.resource_type == 'paper':
                    a={
                        "source_type":source.resource_type,
                        "paper":get_paper_by_id(db,source.resource_id)
                    }
                    sources_List.append(a)
                elif source.resource_type == 'video':
                    a={
                        "source_type":source.resource_type,
                        "vedio":get_video_by_id(db,source.resource_id)
                    }
                    sources_List.append(a)
                elif source.resource_type == 'picture':
                    a={
                        "source_type":source.resource_type,
                        "picture":get_image_by_id(db,source.resource_id)
                    }
                    sources_List.append(a)
        # print("及执行")
        # print(sources_List)
        return sources_List
    # 4. 将对象转为 dict 格式（便于 JSON 序列化）
    def folder_to_dict(folder):
        return {
            "id": folder.id,
            "name": folder.name,
            "children": {
                "source_List": get_resource(folder),
                "folder_List": [folder_to_dict(child) for child in getattr(folder, 'children', [])]
            }
        }


    tree_list = [folder_to_dict(folder) for folder in root_folders]
    print(tree_list)
    # 返回以 user_id 为 key 的字典结构
    return {user_id: tree_list}
def get_user_only_folder_tree(db: Session, user_id: int):
    folders = db.query(Folder).options(
        joinedload(Folder.sources),
        joinedload(Folder.children)  # 预加载 children
    ).filter(Folder.user_id == user_id).all()

    if not folders:
        return {user_id: []}

    # 2. 构建 id -> folder 字典
    folder_map = {folder.id: folder for folder in folders}

    # 3. 构建树形结构
    root_folders = []
    for folder in folders:
        if folder.parent_id is None:
            root_folders.append(folder)
        else:
            parent = folder_map.get(folder.parent_id)
            if parent:
                # 确保 parent 有 children 属性
                if not hasattr(parent, 'children'):
                    parent.children = []
                # 避免重复添加子节点
                if folder not in parent.children:
                    parent.children.append(folder)
    # 4. 将对象转为 dict 格式（便于 JSON 序列化）
    def folder_to_dict(folder):
        return {
            "id": folder.id,
            "name": folder.name,
            "children": [folder_to_dict(child) for child in getattr(folder, 'children', [])]
        }


    tree_list = [folder_to_dict(folder) for folder in root_folders]
    print(tree_list)
    # 返回以 user_id 为 key 的字典结构
    return {user_id: tree_list}

def create_folder(db: Session, name,parent_id,user_id):
    # 1. 解析 folder_data
    # name = folder_data.get('name')
    # parent_id = folder_data.get('parent_id')  # 可以为 None
    # user_id = folder_data.get('user_id')

    # 2. 创建新的 Folder 实例
    new_folder = Folder(
        name=name,
        parent_id=parent_id,
        user_id=user_id
    )

    # 3. 添加到数据库会话
    db.add(new_folder)

    # 4. 提交事务
    db.commit()
    db.refresh(new_folder)
    return new_folder

def delete_folder(db: Session, folder_id):
    # 1. 查询要删除的文件夹
    folder = db.query(Folder).filter(Folder.id == folder_id).first()

    if not folder:
        return False

    # 2. 删除文件夹
    db.delete(folder)

    # 3. 提交事务
    db.commit()
    return True

def update_folder(db: Session, folder_id:int, folder_name:str,parent_id:int,user_id:int):
    # 1. 查询要更新的文件夹
    folder = db.query(Folder).filter(Folder.id == folder_id).first()

    if not folder:
        return None

    # 2. 更新文件夹信息
    folder.name = folder_name
    folder.parent_id = parent_id
    folder.user_id = user_id
    db.commit()
    db.refresh(folder)
    return folder

def get_folder_by_id(db: Session, folder_id):
    return db.query(Folder).filter(Folder.id == folder_id).first()

if __name__ == '__main__':
    from database.db import SessionLocal
    db = SessionLocal()
    result = get_user_only_folder_tree(db,11)
    print(result)
